﻿using System;
using System.IO;
using System.Windows.Controls;
using System.Xml;
using Avivo.Tools.Sprite.Models;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;

namespace Avivo.Tools.Sprite.Views
{
	public partial class SpriteView : UserControl
	{
		#region Constructor
		public SpriteView()
		{
			InitializeComponent();
			InitializeAvalonEdit();
		}
		#endregion

		#region Public properties
		public SpriteViewModel ViewModel
		{
			get
			{
				return this.DataContext as SpriteViewModel;
			}
		}
		#endregion

		#region Protected methods
		protected void InitializeAvalonEdit()
		{
			try
			{
				IHighlightingDefinition cssHighlighting;
				using (Stream s = this.GetType().Assembly.GetManifestResourceStream("Avivo.Tools.Sprite.Resources.Css.xshd"))
				{
					if (s == null)
					{
						throw new InvalidOperationException("Could not find embedded resource");
					}
					using (XmlReader reader = new XmlTextReader(s))
					{
						cssHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
					}
				}
				HighlightingManager.Instance.RegisterHighlighting("CSS Highlighting", new string[] { ".css" }, cssHighlighting);

				//Work-around for binding to Text property
				this.ViewModel.PropertyChanged += (sender, e) =>
				{
					if (e.PropertyName == "PreviewCssContent")
					{
						textEditor.Text = ViewModel.PreviewCssContent;
					}
				};

				textEditor.SyntaxHighlighting = cssHighlighting;
				textEditor.Text = ViewModel.PreviewCssContent;
			}
			catch
			{
			}
		}
		#endregion
	}
}
